var rolesClass = {
	parent: "parentId",
	pattern: "4H",
	win: null,
	form: null,
	grid: null,
	tree: null,
	statusGrid: null,
	layout: null,
	widgetWin: function(){
		var me = this,
            windows = new dhtmlXWindows();

		me.win = windows.createWindow('window_1', 0, 0, 565, 400);
		me.win.setText('Roles');
		//me.win.clearIcon();
		me.win.button('park').hide();
		me.win.button('minmax1').hide();
		me.win.denyResize();
		me.win.setModal(1);
		me.win.centerOnScreen();
		
		widgetBar(me.win,1);
		me.layout = me.win.attachLayout('3L');
	},
	widgetGrid: function(){
		var me = this,
            cell = this.layout.cells('c');

		cell.setWidth('280');
		cell.hideHeader();
		cell.fixSize(true, true);

		me.statusGrid = cell.attachStatusBar();
		 
		me.grid = cell.attachGrid();		
		me.grid.setHeader("Id,C&oacute;digo,Detalle, Menu");
		me.grid.setColTypes("ro,ro,ro,ro");		
		me.grid.setColAlign("right,left,left,left");
		me.grid.setInitWidths("30,60,*,*");	
		me.grid.setColumnColor("#E5E5E5");

		me.grid.init();
		me.grid.load(mainPath+"index.php/roles/grid_data", function(){
			me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
			me.grid.setColumnHidden(3,true);
		},"json");

	},
	widgetForm: function(){
		var me = this,
            str,
            panel = this.layout.cells('b');

		panel.setWidth('280');
		panel.setHeight('120');
		panel.hideHeader();
		str = [
			{ type:"settings" , labelWidth:80, inputWidth:250, position:"absolute"  },
			{ type:"input" , name:"rol_codigo", label:"Codigo:", labelAlign:"right", validate: "NotEmpty", inputWidth:80, labelLeft:-30, labelTop:25, inputLeft:53, inputTop:25  },
			{ type:"input" , name:"rol_detalle", label:"Detalle:", labelAlign:"right", validate: "NotEmpty", inputWidth:217, labelLeft:-30, labelTop:50, inputLeft:53, inputTop:50  },
			{ type:"hidden" , name:"rol_archivo" },
			{ type:"button" , name:"edit_btn", label:"Button", value:"Modificar", width:"75", inputWidth:75, inputLeft:115, inputTop:75  },
			{ type:"button" , name:"save_btn", label:"Button", value:"Guardar", width:"75", inputWidth:75, inputLeft:195, inputTop:75  }
		];
		me.form = panel.attachForm(str);
		me.form.lock();
	},
    onEventForm: function(){
        var me = this;

        me.form.attachEvent("onButtonClick", function(name) {
            switch(name){
                case 'save_btn':
                    me.onClickButtonSaveData();
                    break;
                case 'edit_btn':
                    me.onClickButtonEditData();
                    break;
            }
        });
    },
    onClickButtonSaveData: function(){
        var me = this,
            auxFind,
            valCell,
            id,
            data;

        if(me.tree.getAllChecked()){
            me.form.setItemValue('rol_archivo', me.tree.getAllChecked());
            data = me.form.getFormData();
            if(me.form.validate()){
                auxFind = me.grid.findCell(data.rol_codigo,1);
                valCell = (auxFind != '')?me.grid.cells(auxFind[0][0],auxFind[0][1]).getValue():null;
                if(valCell != data.rol_codigo){
                    me.form.send(mainPath+'index.php/roles/save_data', function(loader, response) {
                        if(response > 0){
                            id = me.grid.uid();
                            me.grid.addRow(id, [response,data.rol_codigo,data.rol_detalle,data.rol_archivo]);
                            me.grid.selectRowById(id);
                            me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                            me.form.clear();
                            me.form.lock();
                            actionBar.enableItem('btn_new');
                        }
                        else
                            dhtmlx.alert({
                                text:response
                            });
                    });
                }
                else
                    dhtmlx.alert({
                        text:"Error, ya existe el codigo '"+valCell.toUpperCase()+"', ingrese otro."
                    });
            }
            else
                dhtmlx.alert({
                    text:"Error, Todos los campos de color rojo son necesarios."
                });
        }
        else
            dhtmlx.alert({
                text: "Seleccione por lo menos un Ítem del Arbol, para el acceso del menu superior."
            });
    },
    onClickButtonEditData: function(){
        var me = this,
            rowId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();

        if(me.tree.getAllChecked()){
            me.form.setItemValue('rol_archivo', me.tree.getAllChecked());
            if(me.form.validate()){
                me.form.send(mainPath+'index.php/roles/edit_data?id='+rowId, function(loader, response){
                    if(response == true){
                        me.grid.cells(rowId,2).setValue(me.form.getFormData().rol_detalle);
                        me.grid.cells(rowId,3).setValue(me.tree.getAllChecked());
                        me.grid.clearSelection();
                        me.form.lock();
                        me.form.clear();
                        me.form.setItemFocus('btn_new');
                    }
                    else
                        dhtmlx.alert({
                            text:response
                        });
                });
            }
            else
                dhtmlx.alert({
                    text:"Error, Todos los campos de color rojo son necesarios."
                });
        }
        else
            dhtmlx.alert({
                text: "Selecciones por lo menos un Ítem del Arbol, para el acceso del menu superior."
            });
    },
	widgetTree: function(){
		var me = this,
            cell = me.layout.cells('a');

		cell.setText("Seleccione ítems del Menu");
		me.tree = cell.attachTree();		
		me.tree.enableCheckBoxes(1);
		me.tree.enableThreeStateCheckboxes(true);
		me.tree.setIconsPath(mainPath+'dhtmlx/imgs/');
		me.tree.loadXML(mainPath+'resources/xml/treemenu.xml');
	},
    onEventActionToolBar: function(){
        var me = this;

        actionBar.attachEvent("onClick", function(itemId){
            switch(itemId){
                case 'btn_new':
                    me.onClickButtonNew(itemId);
                    break;
                case 'btn_edit':
                    me.onClickButtonEdit();
                    break;
                case 'btn_erase':
                    me.onClickButtonErase();
                    break;
                case 'btn_clear':
                    me.onClickButtonClear();
                    break;
            }
        });
    },
    onClickButtonNew: function(itemId){
        var me = this;

        actionBar.disableItem(itemId);
        me.form.clear();
        me.form.unlock();
        me.form.enableItem('rol_codigo');
        me.form.setItemFocus('rol_codigo');
        me.form.disableItem('edit_btn');
        me.form.enableItem('save_btn');

        me.tree.setSubChecked('men',false);
        me.tree.setSubChecked('men_inicio',true);
        me.tree.setSubChecked('men_help',true);
    },
    onClickButtonEdit: function(){
        var me = this,
            treeData,
            i,
            id = me.grid.getSelectedRowId();

        if(id != null){
            me.form.unlock();
            actionBar.enableItem('btn_new');
            me.form.disableItem('save_btn');
            me.form.enableItem('edit_btn');
            me.form.setItemValue('rol_codigo', me.grid.cells(id,1).getValue());
            me.form.setItemValue('rol_detalle', me.grid.cells(id,2).getValue());
            me.form.disableItem('rol_codigo');

            treeData = me.grid.cells(id,3).getValue().split(',');
            me.tree.setSubChecked('men',false)
            for(i in treeData){
                me.tree.setCheck(treeData[i],true);
            }
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder editar."
            });
    },
    onClickButtonErase: function(){
        var me = this,
            rowId;

        if(me.grid.getSelectedRowId() != null){
            rowId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();
            dhtmlx.confirm({
                text:"¿Esta seguro que quieres eliminar el Ítem?",
                callback: function(status){
                    if(status == true){
                        me.form.send(mainPath+'index.php/roles/erase_data?id='+rowId, function(loader, response){
                            if(response != true)
                                dhtmlx.alert({
                                    text: response
                                });
                            else{
                                me.grid.deleteSelectedRows();
                                me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                            }
                        });
                    }
                }
            });
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder eliminar."
            });
    },
    onClickButtonClear: function(){
        var me = this;

        me.form.lock();
        me.form.clear();
        me.form.setItemFocus('btn_new');
        actionBar.enableItem('btn_new');
        me.grid.clearSelection();
    },
	widgetMain: function(){
        var me = rolesClass;

		me.widgetWin();
		me.widgetForm();
        me.onEventForm();
		me.widgetTree();
		me.widgetGrid();
        me.onEventActionToolBar();

	}
};